package com.starpl.mobile.android.monthunsae.november.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.starpl.mobile.android.monthunsae.november.R;
import com.starpl.mobile.android.monthunsae.november.common.EventWebViewClient;
import com.starpl.mobile.android.monthunsae.november.common.StarpetWebChromeClient;
import com.starpl.mobile.android.monthunsae.november.domain.UserInfo;
import com.starpl.mobile.android.platform.command.StarplCommand;
import com.starpl.mobile.android.platform.common.FriendTellUtil;
import com.starpl.mobile.android.platform.common.StarplUtil;
import com.starpl.mobile.android.platform.common.VersionUtil;
import com.starpl.mobile.android.platform.common.base.BaseActivity;
import com.starpl.mobile.android.platform.common.base.BaseApplication;
import com.starpl.mobile.android.platform.common.image.ImageDownloader;
import com.starpl.mobile.android.platform.common.network.HttpHandler;

/**
 * 통합적으로 사용할 웹뷰
 * 
 * @author 박우람
 * @since 2011.02.21
 */
public class WebViewActivity extends BaseActivity implements OnClickListener
{
	private static final int CONTEXT_MENU_FRIEND_TELL_TWITTER = 0;
	private static final int CONTEXT_MENU_FRIEND_TELL_FACEBOOK = 1;
	private static final int CONTEXT_MENU_FRIEND_TELL_ME2DAY = 2;
	private static final int CONTEXT_MENU_FRIEND_TELL_KAKAOTALK = 3;
	
	private TextView mTvTopBarTitle;
	private ImageButton mIbSavePicture;
	private ProgressBar mPbLoading;
	private WebView mWvWebView;
	private ProgressDialog mPdProgress;
	
	private String mUrl;
	
	// 이벤트용
	private String mEventTitle = "친구에게 알려보세요";
	private String mEventMessage = "메시지";
	private String mEventUrl = "http://starpl.com";
	
	/* (non-Javadoc)
	 * @see com.starpl.platform.common.base.BaseActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview_activity);
		
		mTvTopBarTitle = (TextView) findViewById(R.id.webview_activity_tv_title);
		mPbLoading = (ProgressBar) findViewById(R.id.webview_activity_pb_loading);
		mWvWebView = (WebView) findViewById(R.id.webview_activity_wv_webview);
		mIbSavePicture = (ImageButton) findViewById(R.id.webview_activity_ib_save_picture);
		
		// 웹뷰 설정
		mWvWebView.getSettings().setJavaScriptEnabled(true);
		mWvWebView.getSettings().setUseWideViewPort(true);
		mWvWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		mWvWebView.getSettings().setLoadsImagesAutomatically(true);
		mWvWebView.getSettings().setSupportZoom(true);
		mWvWebView.getSettings().setBuiltInZoomControls(true);
		mWvWebView.getSettings().setDefaultTextEncodingName("UTF-8");
		mWvWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
		mWvWebView.setWebViewClient(new EventWebViewClient(this));
		mWvWebView.setWebChromeClient(new StarpetWebChromeClient()
		{
			@Override
			public void onProgressChanged(WebView view, int newProgress)
			{
				if(newProgress < 100)
				{
					mPbLoading.setVisibility(View.VISIBLE);
				}
				else if(newProgress >= 100)
				{
					mPbLoading.setVisibility(View.GONE);
				}
				
				mPbLoading.setProgress(newProgress);
				
				super.onProgressChanged(view, newProgress);
			}
		});
		mWvWebView.setInitialScale(100);
		
		// 넘어온 값 할당
		Bundle bundle = getIntent().getExtras();
	    String title = bundle.getString("title");
	    mUrl = bundle.getString("url");
	    int postIdx = bundle.getInt("postIdx", 0);
	    
	    if(title == null)
	    {
	    	alert("상단 타이틀 이름(title)이 설정되지 않았습니다");
	    	return;
	    }
	    else if(mUrl == null && postIdx == 0)
	    {
	    	alert("접속할 주소(url) 또는 글IDX(postIdx)가 설정되지 않았습니다");
	    }
	    else
	    {
	    	// 타이틀바 텍스트 설정
	    	mTvTopBarTitle.setText(title);
	    	
	    	// URL로 호출
	    	if(mUrl != null)
	    	{
	    		// URL주소가 이미지일경우 다운로드 버튼을 보여준다.
	    		if(mUrl.endsWith(".jpg") || mUrl.endsWith(".png") || mUrl.endsWith(".gif"))
	    		{
	    			mIbSavePicture.setVisibility(ImageButton.VISIBLE);
	    			mIbSavePicture.setOnClickListener(this);
	    		}
	    		
	    		mWvWebView.loadUrl(updateHeader(mUrl));
	    	}
	    	// 긴글의 경우 수동으로 호출
	    	else
	    	{
	    		HttpHandler httpHandler = new HttpHandler(this)
	    		{
					@Override
					public void didSucceed(Object result)
					{
						try
						{
							JSONObject object = (JSONObject) result;
							JSONObject data = object.getJSONObject("data");
							String content = data.getString("content");
							content = StarplUtil.escapeHtmlEntities(content);
							mWvWebView.loadData(content, "text/html", "UTF-8");
						}
						catch(JSONException e)
						{
							LOG.e(e.getMessage());
						}
					}
	    		};
	    		UserInfo userInfo = (UserInfo)BaseApplication.getGlobalPersistent("userInfo");
	    		StarplCommand.getLongPost(httpHandler, userInfo.getUserId(), postIdx);
	    	}
	    }
	}

	/* (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v)
	{
		// 이미지 다운로드 상태 표시용 프로그래스바
		mPdProgress = new ProgressDialog(this);
	    mPdProgress.setMessage("이미지 파일을 저장중입니다.");
	    mPdProgress.setIndeterminate(true);
	    mPdProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    mPdProgress.setCancelable(false);
	    mPdProgress.show();
	    
	    // 이미지 다운로드 결과 표시용 핸들러
	    final Handler handler = new Handler()
	    {
	    	public void handleMessage(Message msg)
	    	{
	    		mPdProgress.dismiss();
	    		
	    		switch(msg.what)
	    		{
				case 0:
					toast("저장을 완료하였습니다.");
					break;

				default:
					toast("파일을 저장하는데에 실패하였습니다. SDCARD가 마운트되어있고 용량이 충분한지 확인해주십시오.");
					break;
				}
	    	}
	    };
	    
	    // 이미지 저장용 쓰레드
	    Thread thread = new Thread(new Runnable()
	    {
            public void run()
            {
            	// 현재 보여주는 이미지를 저장합니다.
        		Bitmap downloadedImage = ImageDownloader.download(mUrl);
        		
        		// 이미지 기본 저장 폴더를 sdcard/Starpl/Starpet/ 으로 변경
        		String extStorageDirectory = Environment.getExternalStorageDirectory().toString() + "/Starpl/Starpet/";
        		OutputStream outStream = null;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                String filename = sdf.format(new Date());
                
                // sdcard/Starpl/Starpet/ 폴더 생성
                File folder = new File(extStorageDirectory);

                // 이미지 저장 기본 폴더가 존재하지 않으면 폴더를 생성한다.
                if(!folder.exists())
                {
                	folder.mkdirs();
                }
                
        		File file = new File(extStorageDirectory, filename + ".jpg");
        		
        		try
        		{
        			outStream = new FileOutputStream(file);
        			downloadedImage.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
        			outStream.flush();
        			outStream.close();
        			MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
        			
        			handler.sendEmptyMessage(0);
        		}
        		catch(Exception e)
        		{
        			handler.sendEmptyMessage(1);
        		}
        		
            }
        });
        thread.start();
	}
	
	/**
	 * 주소에 필요한 추가 정보를 업데이트 합니다.
	 * 
	 * @param url 주소
	 * @return 추가 정보가 더해진 URL
	 */
	private String updateHeader(String url)
	{
		String brandService = BaseApplication.getConfigPersistent("brandService");
		String version = VersionUtil.getVersion(this);
		
		if(url.contains("?"))
		{
			url = url + "&brandService=" + brandService;
		}
		else
		{
			url = url + "?brandService=" + brandService;
		}
		
		url = url + "&clientVersion=" + version;
		
		return url;
	}
	
	/**
	 * 친구에게 알리기에 사용할 이벤트 메시지를 정의합니다.
	 * 
	 * @param title 제목
	 * @param message 메시지
	 * @param url 주소
	 */
	public void updateEventMessage(String title, String message, String url)
	{
		this.mEventTitle = title;
		this.mEventMessage = message;
		this.mEventUrl = url;
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onContextItemSelected(final MenuItem item)
	{
		FriendTellUtil frtiendTell = FriendTellUtil
			.getInstance()
			.setMessage(mEventMessage)
			.setUrl(mEventUrl);
		
		switch(item.getItemId())
		{
		case CONTEXT_MENU_FRIEND_TELL_KAKAOTALK:
			frtiendTell.showKakaoTalk(WebViewActivity.this);
			break;

		case CONTEXT_MENU_FRIEND_TELL_TWITTER:
			frtiendTell.showTwitter(WebViewActivity.this);
			break;
			
		case CONTEXT_MENU_FRIEND_TELL_FACEBOOK:
			frtiendTell.showFacebook(WebViewActivity.this);
			break;
			
		case CONTEXT_MENU_FRIEND_TELL_ME2DAY:
			frtiendTell.showMe2Day(WebViewActivity.this, "스타플+안드로이드+아이폰");
			break;
		}
		
		return false;
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
	 */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
	{
		super.onCreateContextMenu(menu, v, menuInfo);
		
		menu.setHeaderTitle(mEventTitle);
		menu.add(0, CONTEXT_MENU_FRIEND_TELL_KAKAOTALK, 0, "카카오톡");
		menu.add(0, CONTEXT_MENU_FRIEND_TELL_TWITTER, 0, "트위터");
		menu.add(0, CONTEXT_MENU_FRIEND_TELL_FACEBOOK, 0, "페이스북");
		menu.add(0, CONTEXT_MENU_FRIEND_TELL_ME2DAY, 0, "미투데이");
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.common.base.BaseActivity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// 2011.10.17 웹뷰액티비티에서 옵션메뉴 제거
		return false;
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		// 뒤로가기 버튼
		if(keyCode == KeyEvent.KEYCODE_BACK)
		{
			// 히스토리가 있으면
			if(mWvWebView.canGoBack())
			{
				mWvWebView.goBack();
				return true;
			}
		}
		
		return super.onKeyDown(keyCode, event);
	}
	
}